package cn.tradewin.pmp.services.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;

import cn.tradewin.pmp.persist.client.UsersMapper;
import cn.tradewin.pmp.persist.model.Users;
import cn.tradewin.pmp.services.UsersService;

public class UsersServiceImpl implements UsersService {

	@Inject
	private Logger log;
	
	@Inject
	private SqlSessionFactory sqlSessionFactory;
	
	@Override
	public Users getUser(String userid) {
		try {
			SqlSession session = sqlSessionFactory.openSession();
			UsersMapper mapper = session.getMapper(UsersMapper.class);
			return mapper.selectByPrimaryKey(userid);
		} catch (Exception e) {
			log.debug(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int lockUser(String id) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			UsersMapper mapper = session.getMapper(UsersMapper.class);
			int count = mapper.lockUser(id);
			if (count < 0) {
				session.rollback();
				throw new RuntimeException("failure lock account [" + id + "]");
			}
			session.commit();
			return count;
		} catch (Exception e) {
			if (session != null) {
				session.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
	
}
